package com.rich.dmr.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.rich.dmr.R;
import com.rich.dmr.adapter.RxFrequencyGridAdapter;
import com.rich.dmr.databases.DataBaseConnection;
import com.rich.dmr.handler.DmrHandler;
import com.rich.dmr.model.ChannelModel;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.SoundPoolUtils;
import java.util.ArrayList;
import java.util.List;
import rich.dmr.DmrManager;

public class RxFrequencyActivity extends BaseActivity implements View.OnClickListener ,DmrHandler.HandlerCallBack {
    private String TAG = "rich---RxFrequencyActivity";
    private DmrManager dmrManager;
    private List<ChannelModel> frequencyList = new ArrayList<>();
    private RxFrequencyGridAdapter adapter;
    private RecyclerView recyclerView;
    private int mDevHitCountdown;
    private Toast mDevHitToast;
    private static final int TAPS_TO_BE_A_DEVELOPER = 10;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 5:
                    //tcpServer.stop();
                    break;
                case 1:
                    adapter.getList();
                    frequencyList = DataBaseUtils.getInstance(RxFrequencyActivity.this).findChannelList();
                    recyclerView.smoothScrollToPosition(frequencyList.size()-1);
                    break;
                case 2:
                    adapter.getList();
                    break;
                case 3:
                    int color = msg.arg2;
                    Log.d(TAG, "color="+color);
                    if(color != dmrManager.getColorCode()){
                        dmrManager.setColorCode(color);
                        dmrManager.flush();
                    }
                    break;
                case 4:
                    int group = msg.arg2;
                    Log.d(TAG, "group="+group);
                    dmrManager.setGroup(group);
                    dmrManager.flush();
                    break;
            }
        }
    };
    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_frequency);
        SimpleToolbar simpleToolbar = findViewById(R.id.frequency_tools_bar);
        simpleToolbar.seMiddleTitleClickListener(this);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setMainTitle(getString(R.string.digital_receiver_frequency));
        dmrManager = (DmrManager) getSystemService("dmrservice");
        final Button openWrite = findViewById(R.id.write_fre);
        openWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //dmrManager.openOrCloseAdb(true);
                //dmrManager.skipAdbConfirm(true);
                //openWrite.setEnabled(false);
            }
        });


        DataBaseConnection dataBaseConnection = new DataBaseConnection(this);
        dataBaseConnection.getWritableDatabase();
        DmrHandler.getInstance().setHandlerCallBack(this);
        recyclerView = findViewById(R.id.all_frequency);
        recyclerView.setLayoutManager(new RxFrequencyActivity.MyStaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        adapter = new RxFrequencyGridAdapter(RxFrequencyActivity.this,3);
        recyclerView.setAdapter(adapter);
        adapter.setOnClickListener(new RxFrequencyGridAdapter.OnItemClickListener() {
            @Override
            public void ItemClickListener(View view, int position) {
                frequencyList = DataBaseUtils.getInstance(RxFrequencyActivity.this).findChannelList();
                dmrManager.setReceiveFrequency(frequencyList.get(position).getRxChannel());
                dmrManager.flush();
                handler.sendEmptyMessageDelayed(2,100);
                SoundPoolUtils.getInstance(RxFrequencyActivity.this).playSound(false);
            }

            @Override
            public void ItemLongClickListener(View view, final int position) {

            }
        });
        mDevHitCountdown = TAPS_TO_BE_A_DEVELOPER;
        mDevHitToast = null;
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.txt_left_title:
                finish();
                break;
            case R.id.txt_main_title:
                activeSysWriterFrequency();
                Log.d(TAG,"activeSysWriterFrequency");
                break;
            default:
                break;
        }
    }

    @Override
    public void updateFrequency(Message msg) {
        switch (msg.what){
            case 1:
                adapter.getList();
                frequencyList = DataBaseUtils.getInstance(RxFrequencyActivity.this).findChannelList();
                recyclerView.smoothScrollToPosition(frequencyList.size()-1);
                break;
            case 2:
                adapter.getList();
                break;
        }
    }

    class MyStaggeredGridLayoutManager extends StaggeredGridLayoutManager {


        public MyStaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        MyStaggeredGridLayoutManager(int spanCount, int orientation) {
            super(spanCount, orientation);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //dmrManager.openOrCloseAdb(false);
       // dmrManager.skipAdbConfirm(false);
        DmrHandler.getInstance().removeHandlerCallBack(this);
    }

    public void activeSysWriterFrequency() {
        Log.d(TAG, "mDevHitCountdown=" + mDevHitCountdown);
        if (mDevHitCountdown > 0) {
            mDevHitCountdown--;
            if (mDevHitCountdown == 0) {
                // Add 1 count back, then start password confirmation flow.
                mDevHitCountdown++;
                mDevHitCountdown = 0;
                if (mDevHitToast != null) {
                    mDevHitToast.cancel();
                }
                mDevHitToast = Toast.makeText(this, "write number mode open.",
                        Toast.LENGTH_LONG);
                mDevHitToast.show();
                dmrManager.openOrCloseAdb(true);
                dmrManager.skipAdbConfirm(true);
            } else if (mDevHitCountdown > 0
                    && mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER - 2)) {
                if (mDevHitToast != null) {
                    mDevHitToast.cancel();
                }
                //mDevHitToast = Toast.makeText(this, +mDevHitCountdown + "", Toast.LENGTH_SHORT);
                //mDevHitToast.show();
            }

        } else {
            if (mDevHitToast != null) {
                mDevHitToast.cancel();
            }
            //mDevHitToast = Toast.makeText(this, "dev_already",Toast.LENGTH_LONG);
            //mDevHitToast.show();
        }
    }
}
